package com.dp.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dp.entity.ShopType;
import com.dp.mapper.ShopTypeMapper;
import com.dp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.dp.utils.RedisConstants.CACHE_LIST_KEY;
import static com.dp.utils.RedisConstants.CACHE_LIST_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;




    /**
     *  店铺类型查询业务添加缓存
     * @return
     */
    @Override
    public List<ShopType> queryList() {
        //1. 先从redis 查询 商铺类型
        String s = stringRedisTemplate.opsForValue().get(CACHE_LIST_KEY);
        log.info("json字符串：{}",s);
        List<ShopType> shopTypes = new ArrayList<>();
        //2. 判断是否为空
        if (StrUtil.isNotBlank(s)){
            shopTypes = JSONUtil.toList(s, ShopType.class);
            return shopTypes;
        }
        //3.为空则从mysql 中查询
        shopTypes=this.query().orderByAsc("sort").list();
        //4. 放入redis 缓存
        String toStr = JSONUtil.toJsonStr(shopTypes);
        stringRedisTemplate.opsForValue().set(CACHE_LIST_KEY,toStr,CACHE_LIST_TTL, TimeUnit.MINUTES);
        log.info(shopTypes.toString());
        // 5. 返回
        return shopTypes;
    }
}
